<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use QCloud_WeApp_SDK\Auth\LoginService as LoginService;
use QCloud_WeApp_SDK\Constants as Constants;

class Login extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->library('form_validation');//加载表单验证类库
        $this->load->helper('json');
        $this->output->set_content_type('application/html;charset=utf-8');
    }

    public function index() {
        // 微信授权登录
        if(!isset($_GET['type']))
        {
            send_json([
                'code' => -1,
                'error' => '缺少类型参数'
            ]);

            if($_GET['type'] != 'customer' && $_GET['type'] != 'courier'){
                send_json([
                    'code' => -1,
                    'error' => '类型参数错误'
                ]);
            }
        }
        $result = LoginService::login();

        // 处理额外的传参
//        $param = $this->input->post();
//        $this->form_validation->set_rules('username', '用户名', 'trim|required|min_length[1]|max_length[16]|is_unique[app_user.name]');
//        $this->form_validation->set_message('min_length', '{field}最少1位!');
//        $this->form_validation->set_message('max_length', '{field}最多16位!');
//        $this->form_validation->set_message('is_unique', '{field}已被使用，请换一个吧!');
//        $this->form_validation->set_message('required', '请输入{field}');
//
//        $this->form_validation->run();
//        $re = form_error('username');
        // 过滤输出
//        $shuchu = mJson_encode(array('res'=>$re,'haha'=>null,'ee'=>'null','gg'=>'NULL','dd'=>NULL));
        if ($result['loginState'] === Constants::S_AUTH) {
            // 返回角色类型 和 ID
            if(!isset($result['userinfo']['userinfo']->uid) || $result['userinfo']['userinfo']->uid)
            {
                $this->json([
                    'code' => -1,
                    'error' => '没有该用户'
                ]);
            }
            $rk = LoginService::checkType($result['userinfo']['userinfo']->uid,$_GET['type']);
            if(!$rk)
            {
                $this->json([
                    'code' => -1,
                    'error' => '没有该用户'
                ]);
            }
            $result['userinfo']['userinfo']->type = $rk['type'];
            if($rk['type'] == 'app_user')
            {
                $result['userinfo']['userinfo']->phone = $rk['phone'];
                $result['userinfo']['userinfo']->deposit = $rk['deposit'];
            }
            log_message('error','登录日志'.json_encode($result));
            $this->json([
                'code' => 0,
                'data' => $result['userinfo']
            ]);
        } else {
            $this->json([
                'code' => -1,
                'error' => $result['error']
            ]);
        }
    }
}
